package interfaceGrafica;

import baseDeDatos.GestorBD;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.MalformedURLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class Loguearse extends javax.swing.JFrame {
    private GestorBD baseDeDatos;
    private Grafica padre;
    private String url;
    private String user;
    private String pass;
    private String path = "config/baseDeDatos.xml";
    
    public Loguearse(Grafica p) 
    {
        padre = p;
        cargarDatosBDxml();
        initComponents();
        this.userTextField.setText(user);
        this.passwordTextField.setText(pass);
        
    }

    // Cargar datos desde XML
    private void cargarDatosBDxml()
    {
        try {
            Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(path);
            
            Node bd = doc.getElementsByTagName("bd").item(0);
            
            if (bd.getNodeType() == Node.ELEMENT_NODE)
            {
                Element elemento = (Element) bd;
                url = getTagValue("url",elemento);
                user = getTagValue("user",elemento);
                pass = getTagValue("pass",elemento);
            }
        } catch (MalformedURLException ex) {
            Logger.getLogger(GestorBD.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ParserConfigurationException ex) {
            Logger.getLogger(GestorBD.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SAXException ex) {
            Logger.getLogger(GestorBD.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(GestorBD.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
    private String getTagValue(String tag, Element elemento) {
        NodeList lista = elemento.getElementsByTagName(tag).item(0).getChildNodes();
        if (lista.getLength() != 0)
        {   Node valor = (Node) lista.item(0);
            return valor.getNodeValue();
        }
        return "";
    }
    
    private String getTextXML()
    {
        String text = new String();
        text += "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
        text += "\n\n";
        text += "<bd>\n";
        text += "<url>"+url+"</url>\n";
        text += "<user>"+user+"</user>\n";
        text += "<pass>"+pass+"</pass>\n";
        text += "</bd>";
        return text;
    }
    
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        userLabel = new javax.swing.JLabel();
        userTextField = new javax.swing.JTextField();
        passwordLabel = new javax.swing.JLabel();
        saveCheckBox = new javax.swing.JCheckBox();
        passwordTextField = new javax.swing.JPasswordField();
        acceptButton = new javax.swing.JButton();
        cancelButton = new javax.swing.JButton();
        advertenciaLabel = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
        setTitle("Ingresar");
        setResizable(false);

        userLabel.setText("Usuario");

        passwordLabel.setText("Contraseña");

        saveCheckBox.setText("Guardar contraseña");

        acceptButton.setText("Aceptar");
        acceptButton.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                acceptButtonMouseClicked(evt);
            }
        });

        cancelButton.setText("Cancelar");
        cancelButton.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                cancelButtonMouseClicked(evt);
            }
        });

        advertenciaLabel.setForeground(new java.awt.Color(255, 0, 0));

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(advertenciaLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(userLabel)
                                    .addComponent(passwordLabel))
                                .addGap(18, 18, 18)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(passwordTextField)
                                    .addComponent(userTextField)))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(saveCheckBox)
                                .addGap(0, 0, Short.MAX_VALUE)))
                        .addContainerGap())
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(acceptButton, javax.swing.GroupLayout.DEFAULT_SIZE, 95, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(cancelButton, javax.swing.GroupLayout.PREFERRED_SIZE, 94, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(14, 14, 14))))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(15, 15, 15)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(userLabel)
                    .addComponent(userTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(passwordLabel)
                    .addComponent(passwordTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(12, 12, 12)
                .addComponent(saveCheckBox)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(advertenciaLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(13, 13, 13)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(acceptButton)
                    .addComponent(cancelButton))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void acceptButtonMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_acceptButtonMouseClicked
         user = this.userTextField.getText();
         if(user.equals(""))
         {
             advertenciaLabel.setText("Campo usuario vacio");
         }
         else
         {
             advertenciaLabel.setText("");
             pass = String.valueOf(passwordTextField.getPassword());
             baseDeDatos = new GestorBD(url, user, pass);
             
             if(saveCheckBox.isSelected() && baseDeDatos.conexionExitosa())
             {
                 PrintWriter writer;
                 try {
                     writer = new PrintWriter(new FileWriter(path));
                     writer.println(this.getTextXML());
                     writer.close();
                 } catch (IOException ex) {
                     Logger.getLogger(Loguearse.class.getName()).log(Level.SEVERE, null, ex);
                 }
             }
             padre.setEnabled(true);     // Habilita al padre
             padre.setBD(baseDeDatos);
             this.dispose();
         }
    }//GEN-LAST:event_acceptButtonMouseClicked

    private void cancelButtonMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_cancelButtonMouseClicked
        padre.setEnabled(true);
        this.dispose();
    }//GEN-LAST:event_cancelButtonMouseClicked

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton acceptButton;
    private javax.swing.JLabel advertenciaLabel;
    private javax.swing.JButton cancelButton;
    private javax.swing.JLabel passwordLabel;
    private javax.swing.JPasswordField passwordTextField;
    private javax.swing.JCheckBox saveCheckBox;
    private javax.swing.JLabel userLabel;
    private javax.swing.JTextField userTextField;
    // End of variables declaration//GEN-END:variables

}
